﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Entity;
using School.Entities;
using School.Common;
//using School.Organization;
using School.Accounting;

namespace School.Pages.Accounting
{
    public partial class PaymentOrderEditor : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((IQueryable<int>)Session["privilage"] != null)
            {
                var x = (IQueryable<int>)Session["privilage"];

                if (x.Contains(109) == true)
                {

                    if (!IsPostBack)
                    {
                        LstCampuses.DataSource = Structure.GetCampuses();
                        LstCampuses.DataValueField = "Id";
                        LstCampuses.DataTextField = "Name";
                        LstCampuses.DataBind();

                        LstCertificates.DataSource = Structure.GetCertificatesByCampus(long.Parse(LstCampuses.SelectedValue));
                        LstCertificates.DataValueField = "Id";
                        LstCertificates.DataTextField = "Name";
                        LstCertificates.DataBind();

                        LstCertificates.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الشهادة" });

                        LstStages.DataSource = Structure.GetStagesByCertificate(long.Parse(LstCertificates.SelectedValue));
                        LstStages.DataValueField = "Id";
                        LstStages.DataTextField = "Name";
                        LstStages.DataBind();
                        LstStages.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر المرحلة" });

                        LstGrades.DataSource = Structure.GetGradesByStage(long.Parse(LstStages.SelectedValue));
                        LstGrades.DataValueField = "Id";
                        LstGrades.DataTextField = "Name";
                        LstGrades.DataBind();
                        LstGrades.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الصف" });

                        LstStudents.DataSource = Students.GetStudentsByGrade(long.Parse(LstGrades.SelectedValue));
                        LstStudents.DataValueField = "Id";
                        LstStudents.DataTextField = "Name";
                        LstStudents.DataBind();
                        LstStudents.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الطالب" });
                    }
                }
                else
                    Response.Redirect("../organization/no_privelege.aspx");
            }
            else
                Response.Redirect("../organization/no_privelege.aspx");
        }

        protected void LstCampuses_SelectedIndexChanged(object sender, EventArgs e)
        {
            LstCertificates.DataSource = Structure.GetCertificatesByCampus(long.Parse(LstCampuses.SelectedValue));
            LstCertificates.DataValueField = "Id";
            LstCertificates.DataTextField = "Name";
            LstCertificates.DataBind();

            LstCertificates.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الشهادة" });

            LstStages.DataSource = Structure.GetStagesByCertificate(long.Parse(LstCertificates.SelectedValue));
            LstStages.DataValueField = "Id";
            LstStages.DataTextField = "Name";
            LstStages.DataBind();
            LstStages.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر المرحلة" });

            LstGrades.DataSource = Structure.GetGradesByStage(long.Parse(LstStages.SelectedValue));
            LstGrades.DataValueField = "Id";
            LstGrades.DataTextField = "Name";
            LstGrades.DataBind();
            LstGrades.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الصف" });

            LstStudents.DataSource = Students.GetStudentsByGrade(long.Parse(LstGrades.SelectedValue));
            LstStudents.DataValueField = "Id";
            LstStudents.DataTextField = "Name";
            LstStudents.DataBind();
            LstStudents.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الطالب" });

            FinancePanel.Visible = false;
            Button2.Visible = false;
            Panel1.Visible = false;
        }

        protected void LstCertificates_SelectedIndexChanged(object sender, EventArgs e)
        {
            LstStages.DataSource = Structure.GetStagesByCertificate(long.Parse(LstCertificates.SelectedValue));
            LstStages.DataValueField = "Id";
            LstStages.DataTextField = "Name";
            LstStages.DataBind();
            LstStages.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر المرحلة" });

            LstGrades.DataSource = Structure.GetGradesByStage(long.Parse(LstStages.SelectedValue));
            LstGrades.DataValueField = "Id";
            LstGrades.DataTextField = "Name";
            LstGrades.DataBind();
            LstGrades.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الصف" });

            LstStudents.DataSource = Students.GetStudentsByGrade(long.Parse(LstGrades.SelectedValue));
            LstStudents.DataValueField = "Id";
            LstStudents.DataTextField = "Name";
            LstStudents.DataBind();
            LstStudents.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الطالب" });

            FinancePanel.Visible = false;
            Button2.Visible = false;
            Panel1.Visible = false;
        }

        protected void LstStages_SelectedIndexChanged(object sender, EventArgs e)
        {
            LstGrades.DataSource = Structure.GetGradesByStage(long.Parse(LstStages.SelectedValue));
            LstGrades.DataValueField = "Id";
            LstGrades.DataTextField = "Name";
            LstGrades.DataBind();
            LstGrades.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الصف" });

            LstStudents.DataSource = Students.GetStudentsByGrade(long.Parse(LstGrades.SelectedValue));
            LstStudents.DataValueField = "Id";
            LstStudents.DataTextField = "Name";
            LstStudents.DataBind();
            LstStudents.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الطالب" });

            FinancePanel.Visible = false;
            Button2.Visible = false;
            Panel1.Visible = false;
        }

        protected void LstGrades_SelectedIndexChanged(object sender, EventArgs e)
        {
            LstStudents.DataSource = Students.GetStudentsByGrade(long.Parse(LstGrades.SelectedValue)).Where(x => x.Status_Id > 4).Select(x => new { x.Id, Name = x.Ar_FirstName + " " + x.Ar_SecondName + " " + x.Ar_ThirdNmae + " " + x.Ar_FourthName });
            LstStudents.DataValueField = "Id";
            LstStudents.DataTextField = "Name";
            LstStudents.DataBind();
            LstStudents.Items.Insert(0, new ListItem() { Value = "0", Text = "اختر الطالب" });

            FinancePanel.Visible = false;
            Button2.Visible = false;
            Panel1.Visible = false;
        }

        protected void LstStudents_SelectedIndexChanged(object sender, EventArgs e)
        {
            HfStudentId.Value = LstStudents.SelectedValue;
            HfStudentId_ValueChanged(null, null);
        }

        protected void LstExpenses_SelectedIndexChanged(object sender, EventArgs e)
        {
            long expense = long.Parse(LstExpenses.SelectedValue);
            long student = long.Parse(LstStudents.SelectedValue);

            LstPayments.DataSource = PaymentOrder.GetPayments(expense, student).Select(x => new { PaymentName = DateTime.Parse(x.Due_Date.ToString()).ToShortDateString() + " " + x.Value.ToString(), x.Id });
            LstPayments.DataValueField = "Id";
            LstPayments.DataTextField = "PaymentName";
            LstPayments.DataBind();

            var payment = PaymentOrder.GetPayment(long.Parse(LstPayments.SelectedValue));

            LblPaymentValue.Text = payment.Value.ToString();

            int studentId = int.Parse(LstStudents.SelectedValue);

            int fatherjobId = 0, fatherStatusId = 0, MotherJobId = 0, MotherStatusId = 0, brothers = 0;

            if (School.Common.StudentData.getfatherjob(studentId).FirstOrDefault() != null)
                fatherjobId = School.Common.StudentData.getfatherjob(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getfatherStatus(studentId).FirstOrDefault() != null)
                fatherStatusId = School.Common.StudentData.getfatherStatus(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getmotherjob(studentId).FirstOrDefault() != null)
                MotherJobId = School.Common.StudentData.getmotherjob(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getmotherStatus(studentId).FirstOrDefault() != null)
                MotherStatusId = School.Common.StudentData.getmotherStatus(studentId).FirstOrDefault().Id;

            brothers = StudentData.getBrothersCount(studentId);

            GridView1.DataSource = Finance.GetExpenseDiscounts(expense, father_job: fatherjobId, mother_job: MotherJobId, father_status: fatherStatusId, mother_status: MotherStatusId, brothers: brothers, studentId: studentId, value: payment.Value);
            GridView1.DataBind();

        }

        protected void LstPayments_SelectedIndexChanged(object sender, EventArgs e)
        {
            var payment = PaymentOrder.GetPayment(long.Parse(LstPayments.SelectedValue));

            LblPaymentValue.Text = payment.Value.ToString();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            CalculateValue();
        }

        protected string GetType(object type)
        {
            return type.ToString() == "1" ? "مبلغ" : "نسبة";
        }

        protected string GetValue(object type, object value)
        {
            if (type.ToString() == "1")
                return value.ToString() + " جنيه";
            else
            {
                var x = String.Format("{0:0.00}", value);
                return x + " جنيه";
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            var discounts = CalculateValue();

            long number = PaymentOrder.AddPaymentOrder(new ACC_Payment_Order()
            {
                Student_Id = long.Parse(HfStudentId.Value),
                Payment_Id = long.Parse(LstPayments.SelectedValue),
                Value = decimal.Parse(LblFinalValue.Text)
            }, discounts);

            //Response.Redirect("PaymentOrders.aspx?Number=" + number.ToString());
            PaymentOrderGrid.DataSource = Voucher.GetPaymentOrdersByNumber(number);
            PaymentOrderGrid.DataBind();
            Panel1.Visible = true;
            //FinancePanel.Visible = false;
        }

        protected List<ACC_Payment_Order_Discounts> CalculateValue()
        {
            decimal fv = decimal.Parse(LblPaymentValue.Text);
            decimal ov = decimal.Parse(LblPaymentValue.Text);

            List<ACC_Payment_Order_Discounts> discounts = new List<ACC_Payment_Order_Discounts>();

            foreach (GridViewRow x in GridView1.Rows)
            {
                CheckBox ch = (CheckBox)x.FindControl("ChkDiscount");
                Label type = (Label)x.FindControl("LblType");
                Label value = (Label)x.FindControl("LblValue");
                Label DId = (Label)x.FindControl("LblDiscountId");

                if (ch.Checked)
                {
                    ACC_Payment_Order_Discounts discount = new ACC_Payment_Order_Discounts();

                    discount.Type = byte.Parse(type.Text);
                    discount.Discount_Id = long.Parse(DId.Text);
                    discount.Value = decimal.Parse(value.Text);

                    discounts.Add(discount);

                    fv = fv - decimal.Parse(value.Text);

                }
            }

            LblFinalValue.Text = fv > 0 ? fv.ToString() : "0.00";

            return discounts;
        }

        protected void HfStudentId_ValueChanged(object sender, EventArgs e)
        {
            long selectedStudent;

            if (long.TryParse(HfStudentId.Value, out selectedStudent))
            {
                StudentsPanel.Visible = false;

                var expenses = Expense.GetExpensesByStudent(selectedStudent)
                    .Where(x => x.ACC_Expense_Payments.Count() > 0);

                LstExpenses.DataSource = expenses;
                LstExpenses.DataValueField = "ID";
                LstExpenses.DataTextField = "Name";
                LstExpenses.DataBind();

                if (LstExpenses.Items.Count > 0)
                {
                    FinancePanel.Visible = true;
                    Button2.Visible = true;
                }
                else
                    return;
            }

            long expense = long.Parse(LstExpenses.SelectedValue);
            long student = long.Parse(LstStudents.SelectedValue);

            LstPayments.DataSource = PaymentOrder.GetPayments(expense, student).Select(x => new { XName = DateTime.Parse(x.Due_Date.ToString()).ToShortDateString() + " " + x.Value.ToString(), x.Id });
            LstPayments.DataValueField = "Id";
            LstPayments.DataTextField = "XName";
            LstPayments.DataBind();

            var payment = PaymentOrder.GetPayment(long.Parse(LstPayments.SelectedValue));

            LblPaymentValue.Text = payment.Value.ToString();

            int studentId = int.Parse(LstStudents.SelectedValue);

            int fatherjobId = 0, fatherStatusId = 0, MotherJobId = 0, MotherStatusId = 0, brothers = 0;

            if (School.Common.StudentData.getfatherjob(studentId).FirstOrDefault() != null)
                fatherjobId = School.Common.StudentData.getfatherjob(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getfatherStatus(studentId).FirstOrDefault() != null)
                fatherStatusId = School.Common.StudentData.getfatherStatus(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getmotherjob(studentId).FirstOrDefault() != null)
                MotherJobId = School.Common.StudentData.getmotherjob(studentId).FirstOrDefault().Id;

            if (School.Common.StudentData.getmotherStatus(studentId).FirstOrDefault() != null)
                MotherStatusId = School.Common.StudentData.getmotherStatus(studentId).FirstOrDefault().Id;

            brothers = StudentData.getBrothersCount(studentId);

            GridView1.DataSource = Finance.GetExpenseDiscounts(expense, father_job: fatherjobId, mother_job: MotherJobId, father_status: fatherStatusId, mother_status: MotherStatusId, brothers: brothers, studentId: studentId, value: payment.Value);
            GridView1.DataBind();
        }

        protected void BtnSearch_Click(object sender, EventArgs e)
        {
            long id = 0;
            string name = null;

            long.TryParse(TxtStudentNumber.Text, out id);
            name = TxtStudentName.Text;
            
            var d = Students.Search(id, name);

            if (d.Count() > 0)
            {
                StudentsGrid.DataSource = d;
                StudentsGrid.DataBind();
                StudentsPanel.Visible = true;
                StudentsGrid.Visible = true;
                LblSearchNotFound.Visible = false;
            }
            else
            {
                StudentsPanel.Visible = true;
                LblSearchNotFound.Visible = true;
                StudentsGrid.Visible = false;
            }

            TxtStudentName.Text = "";
            TxtStudentNumber.Text = "";
        }

        protected void StudentsGrid_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            HfStudentId.Value = ((Label)StudentsGrid.Rows[int.Parse(e.CommandArgument.ToString())].FindControl("LblStudentId")).Text;
            StudentsPanel.Visible = false;
            HfStudentId_ValueChanged(null, null);            
        }        
    }
}